package com.nowcoder.community.config;

import com.nowcoder.community.constant.UserConstant;
import com.nowcoder.community.util.CommunityUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Security配置类
 * @author 花木凋零成兰
 * @date 2024/3/28 15:26
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) throws Exception {
        // 配置不需要权限访问的资源
        web.ignoring().antMatchers("/resources/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 访问授权 配置哪些访问 需要哪些权限才能访问
        http.authorizeRequests()
                .antMatchers(
                    "/user/setting",    // 用户修改
                    "/user/upload",     // 用户上传文件
                    "discuss/add",      // 帖子发布
                    "comment/add/**",   // 评论帖子或回复
                    "letter/**",        // 私信相关
                    "/like",            // 点赞
                    "/follow",          // 关注
                    "unfollow"          // 取消关注
                )
                .hasAnyAuthority(
                    UserConstant.AUTHORITY_USER,
                    UserConstant.AUTHORITY_ADMIN,
                    UserConstant.AUTHORITY_MODERATOR
                )
                .antMatchers(   // 设置加精 和 置顶 权限 只有版主可以
                        "/discuss/top",
                        "/discuss/wonderful"
                )
                .hasAnyAuthority(
                        UserConstant.AUTHORITY_MODERATOR
                )
                .antMatchers(   // 设置删帖权限 只有管理员能用
                        "/discuss/delete",
                        "/data/**",
                        "/actuator/**"
                )
                .hasAnyAuthority(
                        UserConstant.AUTHORITY_ADMIN
                )
                .anyRequest().permitAll()  // 表示除了上述请求外 都可任意访问
                .and().csrf().disable();    // 禁用了CSRF检查
        // 配置权限不够时 如何处理
        http.exceptionHandling()
                // 配置未登录时如何处理
                .authenticationEntryPoint(new AuthenticationEntryPoint() {
                    @Override
                    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
                        // 判断当前请求是 同步还是异步;  异步要求返回为JSON；同步返回HTML
                        String xRequestedWith = request.getHeader("x-requested-with");
                        if ("XMLHttpRequest".equals(xRequestedWith)) {  // 如果是异步请求
                            // 需要响应一个JSON字符串
                            response.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer = response.getWriter();
                            writer.write(CommunityUtil.getJSONString(403, "你还没有登陆噢!"));
                        } else {    // 反之 如果是同步请求
                            // 重定向到 登录界面
                            response.sendRedirect(request.getContextPath() + "/login");
                        }
                    }
                })
                // 配置登录后 权限不足如何处理
                .accessDeniedHandler(new AccessDeniedHandler() {
                    @Override
                    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
                        // 判断当前请求是 同步还是异步;  异步要求返回为JSON；同步返回HTML
                        String xRequestedWith = request.getHeader("x-requested-with");
                        if ("XMLHttpRequest".equals(xRequestedWith)) {  // 如果是异步请求
                            // 需要响应一个JSON字符串
                            response.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer = response.getWriter();
                            writer.write(CommunityUtil.getJSONString(403, "抱歉；你还没有访问此功能的权限噢!"));
                        } else {    // 反之 如果是同步请求
                            // 重定向到 无权限界面
                            response.sendRedirect(request.getContextPath() + "/denied");
                        }
                    }
                });
        // Spring Security底层默认 会自动拦截 /logout 请求 并进行退出处理
        // 需要覆盖其默认退出逻辑，执行自己的退出代码
        http.logout().logoutUrl("/securityLogout"); // 覆盖底层请求；执行项目编写的退出处理逻辑
    }
}
